﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Bookkeeping.Core.Persistence;
using Bookkeeping.Persistence.Repositories;
using Bookkeeping.Core.Services;

namespace Bookkeeping.Web
{
    public partial class Month : System.Web.UI.Page
    {
        const string YearKey = "Year";
        const string MonthKey = "Month";

        protected string MonthAndYear
        {
            get
            {
                string monthName = DateTimeHelper.GetMonthName(Date);
                string capitalizedMonthName = Formatter.CapitalizeFirstLetter(monthName);

                return  capitalizedMonthName + " " + Date.Year;
            }
        }

        private DateTime Date
        {
            get
            {
                int year = 0, month = 0;

                bool isYearValid = int.TryParse(Request.QueryString[YearKey], out year);
                bool isMonthValid = int.TryParse(Request.QueryString[MonthKey], out month);

                if (isYearValid && isMonthValid)
                    return new DateTime(year, month, 1);

                return DateTime.Today;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            LoadPosts();
            InitializeMonthNavigationLinks();
        }

        private void LoadPosts()
        {
            using (IPersistenceContext context = new PersistenceContext())
            {
                var posts = context.Posts.GetAllByMonth(Date);

                var budget = new Budget(posts);

                savingsList.Posts = budget.Savings;
                incomesList.Posts = budget.Incomes;
                expensesList.Posts = budget.Expenses;

                totalControl.TotalExcludingSavings = budget.TotalExcludingSavings;
                totalControl.TotalIncludingSavings = budget.TotalIncludingSavings;
            }
        }

        private void InitializeMonthNavigationLinks()
        {
            string linkFormat = "Month.aspx?{0}={1}&{2}={3}";

            DateTime previousMonth = DateTimeHelper.GetPreviousMonth(Date);
            DateTime nextMonth = DateTimeHelper.GetNextMonth(Date);

            previousMonthLink.HRef = string.Format(linkFormat, YearKey, previousMonth.Year, MonthKey, previousMonth.Month);
            nextMonthLink.HRef = string.Format(linkFormat, YearKey, nextMonth.Year, MonthKey, nextMonth.Month);
        }

        protected void submitAddPostButton_Click(object sender, EventArgs e)
        {
            expensesList.Posts = new List<Bookkeeping.Core.Entities.Post>();
            expensesList.RefreshPostList();

            addPostButton.Text = "postback";
            mainUpdatePanel.Update();
        }
    }
}
